package org.rency.common.messager.service.impl;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.jsoup.Connection.Response;
import org.rency.common.messager.beans.EmailEntity;
import org.rency.common.messager.beans.SMSAlidayuEntity;
import org.rency.common.messager.beans.SMSPlateform;
import org.rency.common.messager.beans.SMSWebChineseEntity;
import org.rency.common.messager.exception.MessageException;
import org.rency.common.messager.service.MessageService;
import org.rency.common.messager.support.taobao.api.ApiException;
import org.rency.common.messager.support.taobao.api.DefaultTaobaoClient;
import org.rency.common.messager.support.taobao.api.TaobaoClient;
import org.rency.common.messager.support.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import org.rency.common.messager.support.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.rency.common.utils.domain.SYSDICT;
import org.rency.common.utils.tool.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class DefaultMessageServiceImpl implements MessageService {
	
	private static final Logger logger = LoggerFactory.getLogger(DefaultMessageServiceImpl.class);
	
	private JavaMailSender mailSender;
	
	@Override
	public boolean sendEmail(EmailEntity entity) throws MessageException{
		logger.info("开始发送邮件:"+entity.toString());
		try{
			MimeMessage mimeMsg = mailSender.createMimeMessage();
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMsg,false,SYSDICT.CHARSET);
			
			String[] tos = new String[entity.getTo().size()];
			for(int i=0;i<entity.getTo().size();i++){
				tos[i] = entity.getTo().get(i);
			}
			messageHelper.setTo(tos);
			
			String[] ccs = new String[entity.getCc().size()];
			for(int i=0;i<entity.getCc().size();i++){
				ccs[i] = entity.getCc().get(i);
			}
			messageHelper.setCc(ccs);
			
			messageHelper.setFrom(entity.getFrom());
			messageHelper.setSentDate(new Date());
			messageHelper.setSubject(entity.getSubject());
			messageHelper.setText(entity.getContent(),entity.isHtml());
			mailSender.send(mimeMsg);
			return true;
		}catch(Exception e){
			logger.error("发送邮件异常.{}",entity.toString(),e);
			throw new MessageException(e);
		}finally{
			logger.info("发送邮件结束:"+entity.toString());
		}
	}

	@Override
	public boolean sendEmail(String from, String target, String subject,String content, boolean isHtml) throws MessageException{
		EmailEntity email = new EmailEntity();
		email.setHtml(isHtml);
		email.setFrom(from);
		List<String> to = new ArrayList<String>();
		to.add(target);
		email.setTo(to);
		email.setSubject(subject);
		email.setContent(content);
		return this.sendEmail(email);
	}

	public boolean sendSMS(SMSWebChineseEntity entity) throws MessageException {
		logger.info("[{}]发送短信开始:",SMSPlateform.WEBCHINESE,entity.toString());
		entity.validate();
		try{
			Map<String, String> data = new HashMap<String, String>();
			data.put("Uid", entity.getUid()); // 注册的用户名  
			data.put("Key", entity.getKey()); // 注册成功后,登录网站使用的密钥  
			data.put("smsMob", entity.getReceiveMobile()); // 手机号码  
			data.put("smsText", entity.getContent());//设置短信内容
			Response response = null;
			try {
				response = HttpUtils.getResponse(entity.getUrl(), data);
			} catch(SocketTimeoutException e){
				logger.info("发送超时进行重试.{}",e.getMessage());
				try {
					response = HttpUtils.getResponse(entity.getUrl(), data);
				} catch (Exception e1) {
					logger.error("发送短信重试异常.",e);
					throw new MessageException(e1);
				}
			} catch (Exception e) {
				logger.error("发送短信异常.",e);
				throw new MessageException(e);
			}
			if(response == null){
				logger.error("发送短信异常,返回为空.");
				throw new MessageException("发送短信异常,返回为空.");
			}
			int httpCode = response.statusCode();
			int respCode = Integer.parseInt(response.body());
			logger.debug("短信发送成功,服务器返回状态:[{}],返回内容:[{}].",httpCode,respCode);
			if(respCode > 0){
				logger.info("短信发送成功:发送[{}]条.",respCode);
				return true;
			}
			switch(respCode){
				case -1:
					throw new MessageException("没有该用户账户:"+entity.getUid());
				case -2:
					throw new MessageException("接口密钥不正确:"+entity.getUid());
				case -21:
					throw new MessageException("MD5接口密钥加密不正确:"+entity.getUid());
				case -3:
					logger.warn("账户[{}]短信数量不足",entity.getUid());
					logger.info("短信发送成功,但剩余数量不足:返回状态:[{}].",respCode);
					return true;
				case -11:
					throw new MessageException("该用户被禁用:"+entity.getUid());
				case -14:
					throw new MessageException("短信内容出现非法字符:"+entity.getUid());
				case -4:
					throw new MessageException("手机号格式不正确:"+entity.getUid());
				case -41:
					throw new MessageException("手机号码为空:"+entity.getUid());
				case -42:
					throw new MessageException("短信内容为空:"+entity.getUid());
				case -51:
					throw new MessageException("短信签名格式不正确:"+entity.getUid());
				case -6:
					throw new MessageException("IP限制:"+entity.getUid());
				default :
					logger.info("发送短信服务端返回未知状态.[{}]",respCode);
					return false;
			}
		}catch (Exception e) {
			logger.info("[{}]发送短信异常:",SMSPlateform.WEBCHINESE,entity.toString(),e);
			throw new MessageException(e);
		}finally {
			logger.info("[{}]发送短信结束:",SMSPlateform.WEBCHINESE,entity.toString());
			logger.info("发送短信:"+entity.toString());
		}
	}

	public boolean sendSMS(SMSAlidayuEntity entity){
		logger.info("[{}]发送短信开始:",SMSPlateform.ALIDAYU,entity.toString());
		entity.validator();
		try {
			TaobaoClient client = new DefaultTaobaoClient(entity.getSmsAlidayuAddress(), entity.getSmsAlidayuAppkey(), entity.getSmsAlidayuSecret());
			AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
			req.setExtend(entity.getExtend());
			req.setSmsType(entity.getSmsType());
			req.setSmsFreeSignName(entity.getSmsFreeSignName());
			req.setSmsParamString(entity.getSmsParam());
			req.setRecNum(entity.getRecNum());
			req.setSmsTemplateCode(entity.getSmsTemplateCode());
			AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req,entity.getCertPath());
			logger.debug("[{}]发送短信返回内容:[{}].",SMSPlateform.ALIDAYU,rsp.toString());
			if(rsp.isSuccess()){
				return true;
			}else{
				logger.info("[{}]发送短信失败:",SMSPlateform.ALIDAYU,rsp.toString());
				return false;
			}
			
		} catch (ApiException e) {
			e.printStackTrace();
			throw new MessageException("["+SMSPlateform.ALIDAYU.getMessage()+"]发送短信异常", e);
		} catch(Exception e){
			e.printStackTrace();
			throw new MessageException("["+SMSPlateform.ALIDAYU.getMessage()+"]发送短信未知异常", e);
		}finally{
			logger.info("[{}]发送短信结束:",SMSPlateform.ALIDAYU,entity.toString());
		}
	}
	
	public JavaMailSender getMailSender() {
		return mailSender;
	}

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

}
